<script lang="ts" setup>
import { ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { setgradeApi } from '#/api/user/user';
import { getAllApi } from '#/api/user/grade';

const user_id = ref(0);

const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data: { name: string; grade_id: string }[]) => {
          return [{ name: '普通会员', grade_id: 0 },...data].map((item: any) => ({
            label: item.name,
            value: item.grade_id,
          }));
        },
        api: getAllApi,
        class: 'w-full',
      },
      // 字段名
      fieldName: 'grade_id',
      // 界面显示的label
      label: '用户等级',
    },
    {
      fieldName: 'remark',
      label: '管理员备注',
      component: 'Textarea',
      componentProps: {
        rows: 5,
      },
      formItemClass: 'items-start',
      labelClass: 'pt-1',
    },
  ],
  showDefaultActions: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    setgradeApi(user_id.value, values).then((res) => {
      message.success({
        content: res.message,
      });
      drawerApi.close();
    })
    .catch(() => {
      drawerApi.unlock();
    });
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData();
      formApi.resetForm();
      if (data.user_id) {
        user_id.value = data.user_id;
        formApi.setValues({
            grade_id: data.grade_id,
            remark: '',
        });
      }
    }
  },
  overlayBlur: 1,
});


</script>
<template>
  <Drawer title="等级">
    <Form />
  </Drawer>
</template>
